package com.cardone.platform.common.support;

import java.util.List;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.BooleanUtils;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.support.TaskUtils;

import com.cardone.common.cache.util.CacheUtils;
import com.cardone.context.ContextHolder;
import com.cardone.platform.authority.dto.NavigationDto;
import com.cardone.platform.authority.service.NavigationService;
import com.cardone.platform.configuration.dto.DictionaryTypeDto;
import com.cardone.platform.configuration.dto.SiteDto;
import com.cardone.platform.configuration.service.DictionaryService;
import com.cardone.platform.configuration.service.SiteService;

/**
 * 初始化数据支持
 *
 * @author yaohaitao
 */
@Getter
@Setter
@Slf4j
public class InitDataSupport {

	/**
	 * 是否初始化数据
	 */
	private Boolean initData;

	/**
	 * 异步调用
	 */
	private TaskExecutor taskExecutor;

	/**
	 * 初始化
	 */
	public void init() {
		if (BooleanUtils.isNotTrue(this.initData)) {
			return;
		}

		if (this.taskExecutor == null) {
			return;
		}

		this.taskExecutor.execute(TaskUtils.decorateTaskWithErrorHandler(new Runnable() {
			@SuppressWarnings("unchecked")
			@Override
			public void run() {
				CacheUtils.flush();

				/**
				 * 配置集合
				 */
				List<DictionaryTypeDto> dictionaryTypeList = null;

				if (ContextHolder.getApplicationContext().containsBean("c1-dictionaryTypeList")) {
					dictionaryTypeList = (List<DictionaryTypeDto>) ContextHolder.getApplicationContext().getBean("c1-dictionaryTypeList");

					ContextHolder.getBean(DictionaryService.class).init(dictionaryTypeList);
				}

				/**
				 * 站集合
				 */
				List<SiteDto> siteList = null;

				if (ContextHolder.getApplicationContext().containsBean("c1-siteList")) {
					siteList = (List<SiteDto>) ContextHolder.getApplicationContext().getBean("c1-siteList");

					ContextHolder.getBean(SiteService.class).init(siteList);
				}

				/**
				 * 导航集合
				 */
				List<NavigationDto> navigationList = null;

				if (ContextHolder.getApplicationContext().containsBean("c1-navigationList")) {
					navigationList = (List<NavigationDto>) ContextHolder.getApplicationContext().getBean("c1-navigationList");

					ContextHolder.getBean(NavigationService.class).init(navigationList);
				}
			}
		}, null, true));
	}
}
